package github

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/wcbing/github-downloader/config"
)

// 下载文件
// url: 下载地址
// filePath: 保存路径
func Download(url, filePath string) (downloaded bool, size string) {
	// 检查是否为 dry-run 模式
	if config.Config["dry-run"] {
		resp, err := http.Head(url)
		if err != nil {
			log.Print(err)
			return
		}
		defer resp.Body.Close()
		if resp.StatusCode != 200 {
			log.Printf("can't download %s because receive %s", url, resp.Status)
			return false, ""
		} else {
			log.Printf("dry-run download: %s", url)
		}
		// 记录文件大小
		if resp.ContentLength < 1000000 {
			size = fmt.Sprintf("%.2fKB", float64(resp.ContentLength)/1000)
		} else {
			size = fmt.Sprintf("%.2fMB", float64(resp.ContentLength)/1000000)
		}
		return true, size
	}
	// 下载文件
	resp, err := http.Get(url)
	if err != nil {
		log.Print(err)
		return false, ""
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		log.Printf("can't download %s because receive %s", url, resp.Status)
		return false, ""
	}
	log.Printf("downloading: %s", url)
	// 记录文件大小
	if resp.ContentLength < 1000000 {
		size = fmt.Sprintf("%.2fKB", float64(resp.ContentLength)/1000)
	} else {
		size = fmt.Sprintf("%.2fMB", float64(resp.ContentLength)/1000000)
	}
	// 下载并保存到文件
	content, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Print(err)
		return false, ""
	}
	if err := os.WriteFile(filePath, content, 0644); err != nil {
		log.Print(err)
		return false, ""
	}
	return true, size
}
